package com.jeady.timetodo.activities.task

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Clear
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.room.Room
import com.jeady.jxcompose.ButtonText
import com.jeady.jxcompose.TipDisplay
import com.jeady.jxcompose.showTip
import com.jeady.timetodo.activities.MainActivity
import com.jeady.timetodo.base.BaseContainer
import com.jeady.timetodo.base.getKeyByValue
import com.jeady.timetodo.database.AppDatabase
import com.jeady.timetodo.database.Task
import com.jeady.timetodo.manager.removeAllNotification
import com.jeady.timetodo.services.RunningService
import com.jeady.timetodo.utils.CurrentDateTime
import com.jeady.timetodo.utils.timeFormat
import kotlin.concurrent.thread

val runningFlag = listOf("进行中", "Running", "running")
class TaskActivity: ComponentActivity() {
    private val taskList = mutableStateListOf<Task>()
    private val TAG = "[TaskActivity] "
    private lateinit var db: AppDatabase
    private var runningService: RunningService? = null
    private val serviceConnection = object: ServiceConnection{
        override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
            Log.d(TAG, "onServiceConnected: $name ${binder?.pingBinder()}")
            binder?.let {
                val localBinder = it as RunningService.LocalBinder
                runningService = localBinder.getService()
            }
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            Log.d(TAG, "onServiceDisconnected: $name")
        }
    }
    enum class ViewType {
        RUNNING,
        FINISHED,
        ALL,
        HISTORY,
    }
    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        db = Room.databaseBuilder(
            applicationContext,
            AppDatabase::class.java, "timetodo"
        ).build()
        Intent(this, RunningService::class.java).also { intent ->
            bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
        }
        setContent {
            BaseContainer{
                val context = LocalContext.current
                var currentViewMode by remember {
                    mutableStateOf(ViewType.RUNNING)
                }
                Column(Modifier.align(Alignment.TopStart)) {
                    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween){
                        ButtonText("主页") {
                            startActivity(Intent(this@TaskActivity, MainActivity::class.java))
                        }
                        var expandMenu by remember{ mutableStateOf(false) }
                        val menuList = remember {
                            mapOf(
                                "查看进行中" to ViewType.RUNNING,
                                "查看已结束" to ViewType.FINISHED,
                                "查看全部" to ViewType.ALL,
                                "全部历史" to ViewType.HISTORY,
                            )
                        }
                        OutlinedButton({
                            expandMenu = true
                        }){
                            Text(menuList.getKeyByValue(currentViewMode)?:"")
                        }
                        val sheetState = rememberModalBottomSheetState()
                        if(expandMenu) {
                            ModalBottomSheet(
                                onDismissRequest = {
                                    expandMenu = false
                                },
                                sheetState = sheetState
                            ) {
                                menuList.forEach {
                                    Box(
                                        Modifier
                                            .fillMaxWidth().height(50.dp)
                                            .background(
                                                if(currentViewMode == it.value) MaterialTheme.colorScheme.primary
                                                else MaterialTheme.colorScheme.background
                                            ).clickable {
                                            currentViewMode = it.value
                                        },
                                        contentAlignment = Alignment.Center
                                    ) {
                                        Text(it.key,
                                            color = if(currentViewMode == it.value) MaterialTheme.colorScheme.background
                                            else MaterialTheme.colorScheme.primary
                                        )
                                    }
                                }
                            }
                        }
                        ButtonText("清空通知") {
                            removeAllNotification(context)
                        }
                        ButtonText("清空历史") {
                            thread {
                                taskList.clear()
                                db.taskDao().deleteAll()
                                runningService?.clearTaskList()
                            }
                        }
                    }
//                    Text("应用完全退出后，记录将自动清除。", Modifier.padding(10.dp, 0.dp), fontSize = 10.sp)
                    LazyColumn(
                        Modifier.fillMaxWidth(),
                        contentPadding = PaddingValues(bottom = 15.dp),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        item {
                            CurrentDateTime(format = "yyyy-MM-dd HH:mm:ss"){
                                if(currentViewMode!= ViewType.HISTORY) {
                                    syncFromService()
                                }
                            }
                        }
                        items(taskList.filter {
                            when(currentViewMode){
                                ViewType.RUNNING ->  runningFlag.contains(it.state)
                                ViewType.FINISHED -> !runningFlag.contains(it.state)
                                ViewType.ALL -> true
                                ViewType.HISTORY -> true
                            }
                        }){
                            TaskItem(it)
                        }
                    }
                    LaunchedEffect(currentViewMode) {
                        if(currentViewMode == ViewType.HISTORY){
                            syncFromDB()
                        }
                    }
                }
                TipDisplay()
            }
        }
    }

    private fun syncFromService() {
        taskList.clear()
        runningService?.getTaskList()?.let { taskList.addAll(it) }
    }
    private fun syncFromDB() {
        thread {
            taskList.clear()
            val tasks = db.taskDao().getAll()
            Log.d(TAG, "onCreate: get tasks $tasks")
            taskList.addAll(tasks)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        db.close()
        unbindService(serviceConnection)
    }
    @Composable
    private fun TaskItem(info: Task){
        val context = LocalContext.current
        Box(
            Modifier.fillMaxWidth(),
            contentAlignment = Alignment.Center
        ){
            Box(
                Modifier
                    .fillMaxHeight()
                    .width(10.dp)
                    .align(Alignment.CenterStart)
                    .background(Color(0xff9f5faf))
            )
            Box(Modifier.padding(10.dp, 5.dp, 10.dp, 0.dp)){
                Surface(shape = RoundedCornerShape(10.dp), shadowElevation = 3.dp) {
                    Row(
                        Modifier.padding(10.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ){
                        Column {

                        }
                        Column(
                            Modifier
                                .weight(1f)
                                .padding(5.dp),
                            verticalArrangement = Arrangement.spacedBy(2.dp)
                        ) {
                            Text("#${if(info.id!=0) info.id else ""} ${info.title}", fontWeight = FontWeight.ExtraBold, fontSize = 20.sp)
                            if(info.description.isNotBlank()){
//                            Text(info.description, fontSize = 15.sp, color=Color.Gray)
                                Text("开始于 ${info.taskId.timeFormat()}", fontSize = 15.sp)
                                if(runningFlag.contains(info.state)) {
                                    Text(
                                        "预计在 ${info.endTime.timeFormat()} 执行",
                                        fontSize = 15.sp,
                                        color = Color.Gray
                                    )
                                }else if(info.state.isNotBlank()){
                                    Text("${info.state} ${info.updateAt}")
                                }
                            }
                        }
                        Column(horizontalAlignment = Alignment.CenterHorizontally) {
                            if(runningFlag.contains(info.state)){
                                Icon(Icons.Outlined.Clear, "删除任务",
                                    Modifier
                                        .clickable {
                                            showTip(
                                                "确定要取消执行该任务吗？",
                                                "不取消",
                                                "确定取消"
                                            ) {
                                                if (it) {
                                                    runningService?.modifyTaskItemInfo(
                                                        info.taskId,
                                                        "已取消"
                                                    )
                                                    showTip("取消任务{${info.title}}成功")
                                                }
                                            }
                                        }
                                        .clip(CircleShape), Color.Red)
                            }else{
                                Icon(Icons.Outlined.Info, "查看详细",
                                    Modifier
                                        .clickable {
                                            startActivity(Intent(context, TaskDetailActivity::class.java).apply{
                                                putExtra("taskId", info.taskId)
                                            })
                                        }
                                        .clip(CircleShape))
                            }
                        }
                    }
                }
            }
        }
    }
}


enum class TaskType{
    NONE,
    STOP_SELF,
    LIGHT_ON,
    LIGHT_OFF,
    LOCK_SCREEN,
    VIBRATE,
    STOP_VIBRATE,
}